package cn.graydove.bot.controller;

import cn.graydove.bot.model.dto.AccountDTO;
import cn.graydove.bot.service.AccountService;
import cn.graydove.bot.service.AdvanceService;
import cn.graydove.bot.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.constraints.NotNull;

@Slf4j
@Controller
public class RegisterController {

    private SmsService smsService;
    private AccountService accountService;
    private AdvanceService advanceService;

    public RegisterController(SmsService smsService, AccountService accountService, AdvanceService advanceService) {
        this.smsService = smsService;
        this.accountService = accountService;
        this.advanceService = advanceService;
    }

    @RequestMapping("/")
    public String register() {
        return "index.html";
    }


    @PostMapping("/validCode")
    @ResponseBody
    public String validCode(Long phone) {
        boolean b = smsService.sendVailCode(phone);
        return b ? "OK" : "ERROR";
    }

    @PostMapping("/register")
    @ResponseBody
    public String register(@NotNull AccountDTO accountDTO) {
        boolean verify = smsService.verify(accountDTO.getValidCode(), accountDTO.getPhone());
        if (!verify) {
            return "验证码错误";
        }
        return accountService.register(accountDTO);
    }

    @PostMapping("/gen_activation_code")
    @ResponseBody
    public String createActivationCode(Long validityTime) {
        String code;
        if (validityTime == null) {
            code = advanceService.createActivationCode(7 * 24 * 60 * 60 * 1000);
        } else {
            code = advanceService.createActivationCode(validityTime);
        }
        return "OK";
    }


}
